#include <stdio.h>
#include <string>
#include <assert.h>
#include <vector>

using std::string;
using std::vector;

string simplifyPath(string p) {
    if (p == "") return "";
    if (p[0] != '/') return "";
    int l = p.size();
    string res = "/";

    vector<string> _v;
    for (int i = 1; i < l; ++i) {
        // p[i-1] is always '/'
        // 1 .
        // 2 /
        // 3 [A-z]
        if (p[i] == '.') {
            // 1 ..
            // 2 ./
            // 3 .file
            if (i == l - 1) {
                break;
            }
            if (p[i+1] == '.' && (i == l - 2 || p[i+2] == '/')) {
                if (!_v.empty()) {
                    _v.pop_back();
                }
                i += 2;
                continue;
            }
            if (p[i+1] == '/') {
                i++;
                continue;
            }
            for (int j = i+1; j < l; ++j) {
                if (p[j] == '/') {
                    _v.push_back(p.substr(i, j-i));
                    i = j;
                    break;
                }
                if (j == l-1) {
                    _v.push_back(p.substr(i, j-i+1));
                    i = j;
                }
            }
        } else if (p[i] == '/') {
            continue;
        } else {
            if (i == l-1) {
                _v.push_back(p.substr(i, 1));
            } else {
                for (int j = i+1; j < l; ++j) {
                    if (p[j] == '/') {
                        _v.push_back(p.substr(i, j-i));
                        i = j;
                        break;
                    }
                    if (j == l-1) {
                        _v.push_back(p.substr(i, j-i+1));
                        i = j;
                    }
                }
            }
        }
    }

    for (int i = 0; i < _v.size(); ++i) {
        res += _v[i];
        if (i != _v.size()-1) {
            res += '/';
        }
    }

    return res;
}

int main() {
    string s[][2] = {
        {"/home/", "/home"},
        {"/../", "/"},
        {"/home//foo/", "/home/foo"},
        {"/a/./b/../../c/", "/c"},
        {"/a/../../b/../c//.//", "/c"},
        {"/a//b////c/d//././/..", "/a/b/c"},
        {"/a/b/c/d/..", "/a/b/c"},
        {"/a/b/c/d/../", "/a/b/c"},
        {"/...", "/..."},
        {"/h", "/h"},
    };
    for (auto ss : s) {
        string res = simplifyPath(ss[0]);
        printf(">>> %s -> %s, got %s\n", ss[0].c_str(), ss[1].c_str(), res.c_str());
        assert(res == ss[1]);
    }
}

